package com.css.zfzx.sjcj.modules.hddcA1InvRgnHasMaterialTable.service.impl;

import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.result.ExcelImportResult;
import com.alibaba.fastjson.JSONObject;
import com.css.bpm.platform.api.local.PlatformAPI;
import com.css.bpm.platform.sys.dict.repository.entity.DictItemEntity;
import com.css.bpm.platform.utils.*;
import com.css.zfzx.sjcj.common.utils.EasyPoiExcelUtil;
import com.css.zfzx.sjcj.common.utils.UpdateUtil;
import com.css.zfzx.sjcj.modules.hddcA1InvRgnHasMaterialTable.repository.HddcA1InvrgnhasmaterialtableNativeRepository;
import com.css.zfzx.sjcj.modules.hddcA1InvRgnHasMaterialTable.repository.HddcA1InvrgnhasmaterialtableRepository;
import com.css.zfzx.sjcj.modules.hddcA1InvRgnHasMaterialTable.repository.entity.HddcA1InvrgnhasmaterialtableEntity;
import com.css.zfzx.sjcj.modules.hddcA1InvRgnHasMaterialTable.service.HddcA1InvrgnhasmaterialtableService;
import com.css.zfzx.sjcj.modules.hddcA1InvRgnHasMaterialTable.viewobjects.HddcA1InvrgnhasmaterialtableQueryParams;
import com.css.zfzx.sjcj.modules.hddcA1InvRgnHasMaterialTable.viewobjects.HddcA1InvrgnhasmaterialtableVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

/**
 * @author zyb
 * @date 2020-11-30
 */
@Service
public class HddcA1InvrgnhasmaterialtableServiceImpl implements HddcA1InvrgnhasmaterialtableService {

	@Autowired
    private HddcA1InvrgnhasmaterialtableRepository hddcA1InvrgnhasmaterialtableRepository;
    @Autowired
    private HddcA1InvrgnhasmaterialtableNativeRepository hddcA1InvrgnhasmaterialtableNativeRepository;

    @Override
    public JSONObject queryHddcA1Invrgnhasmaterialtables(HddcA1InvrgnhasmaterialtableQueryParams queryParams, int curPage, int pageSize,String sort,String order) {
        Page<HddcA1InvrgnhasmaterialtableEntity> hddcA1InvrgnhasmaterialtablePage =this.hddcA1InvrgnhasmaterialtableNativeRepository.queryHddcA1Invrgnhasmaterialtables(queryParams, curPage, pageSize, sort, order);
        JSONObject jsonObject = PlatformPageUtils.formatPageData(hddcA1InvrgnhasmaterialtablePage);
        return jsonObject;
    }


    @Override
    public HddcA1InvrgnhasmaterialtableEntity getHddcA1Invrgnhasmaterialtable(String id) {
        HddcA1InvrgnhasmaterialtableEntity hddcA1Invrgnhasmaterialtable = this.hddcA1InvrgnhasmaterialtableRepository.findById(id).orElse(null);
         return hddcA1Invrgnhasmaterialtable;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public HddcA1InvrgnhasmaterialtableEntity saveHddcA1Invrgnhasmaterialtable(HddcA1InvrgnhasmaterialtableEntity hddcA1Invrgnhasmaterialtable) {
        String uuid = UUIDGenerator.getUUID();
        hddcA1Invrgnhasmaterialtable.setUuid(uuid);
        hddcA1Invrgnhasmaterialtable.setCreateUser(PlatformSessionUtils.getUserId());
        hddcA1Invrgnhasmaterialtable.setCreateTime(PlatformDateUtils.getCurrentTimestamp());
        hddcA1Invrgnhasmaterialtable.setIsValid("1");
        this.hddcA1InvrgnhasmaterialtableRepository.save(hddcA1Invrgnhasmaterialtable);
        return hddcA1Invrgnhasmaterialtable;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public HddcA1InvrgnhasmaterialtableEntity updateHddcA1Invrgnhasmaterialtable(HddcA1InvrgnhasmaterialtableEntity hddcA1Invrgnhasmaterialtable) {
        HddcA1InvrgnhasmaterialtableEntity entity =
                hddcA1InvrgnhasmaterialtableRepository.findByUuidAndIsValid(hddcA1Invrgnhasmaterialtable.getUuid(), "1");
        UpdateUtil.copyNullProperties(entity, hddcA1Invrgnhasmaterialtable);
        hddcA1Invrgnhasmaterialtable.setUpdateUser(PlatformSessionUtils.getUserId());
        hddcA1Invrgnhasmaterialtable.setUpdateTime(PlatformDateUtils.getCurrentTimestamp());
        this.hddcA1InvrgnhasmaterialtableRepository.save(hddcA1Invrgnhasmaterialtable);
        return hddcA1Invrgnhasmaterialtable;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteHddcA1Invrgnhasmaterialtables(List<String> ids) {
        List<HddcA1InvrgnhasmaterialtableEntity> hddcA1InvrgnhasmaterialtableList = this.hddcA1InvrgnhasmaterialtableRepository.findAllById(ids);
        if(!PlatformObjectUtils.isEmpty(hddcA1InvrgnhasmaterialtableList) && hddcA1InvrgnhasmaterialtableList.size() > 0) {
            for(HddcA1InvrgnhasmaterialtableEntity hddcA1Invrgnhasmaterialtable : hddcA1InvrgnhasmaterialtableList) {
                hddcA1Invrgnhasmaterialtable.setIsValid("0");
                hddcA1Invrgnhasmaterialtable.setUpdateUser(PlatformSessionUtils.getUserId());
                hddcA1Invrgnhasmaterialtable.setUpdateTime(new Date());
                this.hddcA1InvrgnhasmaterialtableRepository.save(hddcA1Invrgnhasmaterialtable);
            }
        }
    }

    @Override
    public List<DictItemEntity> getValidDictItemsByDictCode(String dictCode) {
        List<DictItemEntity> validDictItems = PlatformAPI.getDictAPI().getValidDictItemsByDictCode(dictCode);
        return validDictItems;
    }

    @Override
    public void exportFile(HddcA1InvrgnhasmaterialtableQueryParams queryParams, HttpServletResponse response) {
        List<HddcA1InvrgnhasmaterialtableEntity> yhDisasterEntities = hddcA1InvrgnhasmaterialtableNativeRepository.exportYhDisasters(queryParams);
        List<HddcA1InvrgnhasmaterialtableVO> list=new ArrayList<>();
        for (HddcA1InvrgnhasmaterialtableEntity entity:yhDisasterEntities) {
            HddcA1InvrgnhasmaterialtableVO yhDisasterVO=new HddcA1InvrgnhasmaterialtableVO();
            BeanUtils.copyProperties(entity,yhDisasterVO);
            list.add(yhDisasterVO);
        }
        EasyPoiExcelUtil.exportExcel(list,"调查区与面状资料关联表","调查区与面状资料关联表",HddcA1InvrgnhasmaterialtableVO.class,"调查区与面状资料关联表.xls",response);
    }

    @Override
    public String exportExcel(MultipartFile file, HttpServletResponse response) {
        try {
            // 返回的消息
            StringBuilder returnMsg = new StringBuilder();
            // 导入的参数信息
            ImportParams params = new ImportParams();
            // 设置简析的第一行
            params.setHeadRows(1);
            // 是否需要校验
            params.setNeedVerify(true);
            // 获取到Excel数据
            ExcelImportResult<HddcA1InvrgnhasmaterialtableVO> result = ExcelImportUtil.importExcelMore(file.getInputStream(), HddcA1InvrgnhasmaterialtableVO.class, params);
            List<HddcA1InvrgnhasmaterialtableVO> list = result.getList();
            // Excel条数据
            int firstList = list.size();
            StringBuilder sb = new StringBuilder();
            //保存
            saveDisasterList(list, sb);
            returnMsg.append("成功导入" + (result.getList().size() ));
            returnMsg.append(sb);
            if (result.isVerifyFail()) {
                // 校验返回失败行信息
                Iterator<HddcA1InvrgnhasmaterialtableVO> iterator = result.getFailList().iterator();
                while (iterator.hasNext()) {
                    HddcA1InvrgnhasmaterialtableVO yhDisasterVO = iterator.next();
                    String error = "";
                    returnMsg.append("第" + yhDisasterVO.getRowNum() + "行" + yhDisasterVO.getErrorMsg() + "<br/>");
                    returnMsg.append(error);
                }
            }
            return returnMsg.toString();
        } catch (Exception e) {

            return "导入失败，请检查数据正确性";
        }
    }
    /**
     * 批量存入库表并且返回错误数量
     *
     * @param list
     * @param message
     * @return
     */
    public void saveDisasterList( List<HddcA1InvrgnhasmaterialtableVO> list, StringBuilder message) {
        for (int i = 0; i < list.size(); i++) {
            HddcA1InvrgnhasmaterialtableEntity yhDisasterEntity = new HddcA1InvrgnhasmaterialtableEntity();
            HddcA1InvrgnhasmaterialtableVO yhDisasterVO = list.get(i);
            // 将VO数据映射拷贝到库表中
            BeanUtils.copyProperties(yhDisasterVO, yhDisasterEntity);
            saveHddcA1Invrgnhasmaterialtable(yhDisasterEntity);
        }
    }
}
